package com.mongo.api;

import com.tanhua.dubbo.mongo.RecommendUserAPI;
import com.tanhua.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserAPIImpl implements RecommendUserAPI {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findTodayBestByMaxScore(Long toUserId) {
        //1构建Critera
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2构造Query对象，排序之后查找得分最高的那个RecommendUser
        Query query = new Query(criteria).with(Sort.by(Sort.Order.desc("score"))).limit(1);
        //3查找返回
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    @Override
    public List<RecommendUser> queryRecommendUserList(Long toUserId) {
        //1 构建Critera对象
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2 构建Query对象
        Query query = new Query(criteria);
        //3 查询
        List<RecommendUser> list = mongoTemplate.find(query, RecommendUser.class);
        //4 返回
        return list;
    }

    @Override
    public RecommendUser queryJiaRenFateValue(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("toUserId").is(toUserId);
        Query query = new Query(criteria);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(95d);
        }
        return recommendUser;
    }
}
